package org.iabako.client.ui.form.user.enterprise;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Image;
import org.iabako.client.navigation.FailureController;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.ui.form.AbstractForm;
import org.iabako.client.ui.layout.field.*;
import org.iabako.client.ui.layout.widget.validation.ValidationMessage;
import org.iabako.client.user.AuthenticateUserProvider;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.entity.business.Address;
import org.iabako.shared.entity.enumeration.Country;
import org.iabako.shared.entity.user.Enterprise;
import org.iabako.shared.entity.user.User;
import org.iabako.shared.iservice.security.AuthenticateServiceAsync;
import org.iabako.shared.tools.GenericTools;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by jose on 09/02/15.
 */
public class MyEnterpriseConfigForm extends AbstractForm {

    interface MyUiBinder extends UiBinder<HTMLPanel, MyEnterpriseConfigForm> {
    }

    protected MyUiBinder binderForm = GWT.create(MyUiBinder.class);

    @UiField
    InputText enterpriseName;
    @UiField
    InputText addressLine1;
    @UiField
    InputText addressLine2;
    @UiField
    InputText city;
    @UiField
    SelectList country;
    @UiField
    InputText phoneNumber;
    @UiField
    FileUpload logoFileUpload;
    @UiField
    FormPanel logoFileUploadForm;
    @UiField
    Image logoImage;
    @UiField
    HTMLPanel noLogoPanel;
    @UiField
    HTMLPanel logoPanel;
    @UiField
    LabelText deleteLogo;
    @UiField
    LabelText addLogo;
    @UiField
    InputText zipCode;
    @UiField
    InputTextEmail email;
    @UiField
    HTMLPanel waitLogoPanel;
    @UiField
    InputText webSite;

    public MyEnterpriseConfigForm() {
        initWidget(binderForm.createAndBindUi(this));

        setEnterpriseLogoImage();

        setHandlers();
    }

    private void setEnterpriseLogoImage() {
        logoImage.setUrl("/iabako/iabakoServices/getenterpriselogo?reload=" + new Date().getTime());
    }

    private void setHandlers() {

        logoImage.addLoadHandler(new LoadHandler() {
            public void onLoad(LoadEvent event) {
                waitLogoPanel.setVisible(false);
                if (logoImage.getWidth() > 0) {
                    checkImageSize();
                    logoPanel.setVisible(true);
                    noLogoPanel.setVisible(false);
                } else {
                    logoPanel.setVisible(false);
                    noLogoPanel.setVisible(true);
                }
            }
        });

        logoFileUpload.addChangeHandler(new ChangeHandler() {
            public void onChange(ChangeEvent event) {
                if (!checkImage()) {
                    ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "enterprise_form_too_big_logo_error");
                    return;
                }
                logoFileUploadForm.submit();
            }
        });

        logoFileUploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
        logoFileUploadForm.setMethod(FormPanel.METHOD_POST);

        logoFileUploadForm.addSubmitHandler(new FormPanel.SubmitHandler() {
            public void onSubmit(FormPanel.SubmitEvent submitEvent) {
                waitLogoPanel.setVisible(true);
                logoPanel.setVisible(false);
                noLogoPanel.setVisible(false);
            }
        });

        logoFileUploadForm.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
            public void onSubmitComplete(FormPanel.SubmitCompleteEvent event) {

                AuthenticateServiceAsync.Util.getInstance().reloadAuthenticatedUser(new IabakoAsyncCallback<User>() {

                    public void onSuccess(User user) {
                        if (user == null) {
                            FailureController.handleFailure(new Exception("_authentication_error_"));
                            return;
                        }

                        AuthenticateUserProvider.setUser(user);
                        waitLogoPanel.setVisible(false);

                        if (user.getEnterprise().getContentTypeLogo() == null) {
                            ValidationMessage.getFirstFromDOM().showErrorMessage(true, true, "enterprise_form_too_big_logo_error");
                            noLogoPanel.setVisible(true);
                        } else {
                            setEnterpriseLogoImage();
                            ((Enterprise) entity).setContentTypeLogo(user.getEnterprise().getContentTypeLogo());
                        }
                        super.onSuccess(user);
                    }
                });
            }
        });

        addLogo.getLabel().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                logoFileUpload.getElement().<InputElement>cast().click();
            }
        });

        deleteLogo.getLabel().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                logoPanel.setVisible(false);
                noLogoPanel.setVisible(true);
                logoFileUploadForm.reset();
                //To tell server that logo has been deleted
                ((Enterprise) entity).setContentTypeLogo(null);
            }
        });
    }

    public static native boolean checkImage()/*-{

        var input = document.getElementsByName('enterpriseLogoFileUpload_')[0];

        if (input && input.files && input.files[0] && input.files[0].name && input.files[0].size) {
            var url = input.files[0].name;
            var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();

            if (ext != "gif" && ext != "png" && ext != "jpeg" && ext != "jpg") {
                return false;
            }

            if (input.files[0].size > 1000000) {
                return false;
            }
        }
        return true;

    }-*/;

    public void setEnterprise(Enterprise enterprise) {

        entity = enterprise;

        enterpriseName.setValue(enterprise.getName());
        email.setValue(enterprise.getEmail());
        addressLine1.setValue(enterprise.getAddress().getAddressLine1());
        addressLine2.setValue(enterprise.getAddress().getAddressLine2());
        city.setValue(enterprise.getAddress().getCity());
        zipCode.setValue(enterprise.getAddress().getZipCode());
        country.setEnumValue(enterprise.getAddress().getCountry());
        phoneNumber.setValue(enterprise.getPhoneNumber());
        webSite.setValue(enterprise.getWebSite());

        if (enterprise.getContentTypeLogo() == null) {
            waitLogoPanel.setVisible(false);
            logoPanel.setVisible(false);
            noLogoPanel.setVisible(true);
        }
    }

    @Override
    protected List<IField> getMandatoryFields() {
        return Arrays.asList((IField) enterpriseName, addressLine1, city, country, phoneNumber);
    }

    @Override
    protected AbstractEntity getEntity() {

        Enterprise enterprise = (Enterprise) entity;
        enterprise.setName(enterpriseName.getValue());
        enterprise.setEmail(email.getValue());

        Address address = new Address();
        address.setAddressLine1(addressLine1.getValue());
        address.setAddressLine2(addressLine2.getValue());
        address.setCity(city.getValue());
        address.setZipCode(zipCode.getValue());
        address.setCountry((Country) country.getEnumValue());

        enterprise.setAddress(address);
        enterprise.setPhoneNumber(phoneNumber.getValue());
        enterprise.setWebSite(webSite.getValue());

        return enterprise;
    }

    @Override
    public boolean validate() {
        return false;
    }

    private void checkImageSize() {
        String style = logoImage.getElement().getAttribute("style");
        logoImage.getElement().setAttribute("style", style + GenericTools.getHtmlStyleForEnterpriseLogo(logoImage.getWidth(), logoImage.getHeight()));
    }
}
